package com.etooling.pdm.controller;

import com.etooling.framework.entity.AttachFile;
import com.etooling.framework.entity.Employee;
import com.etooling.framework.entity.FileResource;
import com.etooling.framework.entity.ImportDataBatch;
import com.etooling.framework.jpa.JpaQueryBuilder;
import com.etooling.framework.jpa.Specifications;
import com.etooling.framework.repository.AttachFileRepository;
import com.etooling.framework.repository.EmployeeRepository;
import com.etooling.framework.repository.FileResourceRepository;
import com.etooling.framework.repository.ImportDataBatchRepository;
import com.etooling.framework.service.FileUploadSaveService;
import com.etooling.framework.svo.ReplyObj;
import com.etooling.framework.utils.WebUtils;
import com.etooling.germa.repository.ImportBomDetailsRepository;
import com.etooling.pdm.entity.Bom;
import com.etooling.pdm.entity.BomDetail;
import com.etooling.pdm.repository.BomDetailRepository;
import com.etooling.pdm.repository.BomRepository;
import com.etooling.pdm.service.BomService;
import com.etooling.pdm.thread.UploadBomExcelThread;
import com.etooling.pdm.vo.BomDetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


@RequestMapping(value = "/admin/pdm/bom")
@Controller
@EnableAutoConfiguration
public class BomController {
    @Autowired
    private BomRepository bomRepository;
    @Autowired
    private BomService bomService;
    @Autowired
    private BomDetailRepository bomDetailRepository;

    @Autowired
    FileResourceRepository fileResourceRepository;
    @Autowired
    AttachFileRepository attachFileRepository;
    @Autowired
    ImportDataBatchRepository importDataBatchRepository;
    @Autowired
    private ImportBomDetailsRepository importBomDetailsRepository;
    @Autowired
    EmployeeRepository employeeRepository;


    /**
     * 新增BOM
     *
     * @param request
     * @param json
     * @return
     */
    @RequestMapping("addBom")
    @ResponseBody
    ReplyObj addBom(HttpServletRequest request, @RequestParam(defaultValue = "", required = false, value = "json") String json
    ) {
        return bomService.addBom(request, json);
    }


    /**
     * 修改BOM信息
     *
     * @param request
     * @param json
     * @return
     */
    @RequestMapping("updateBom")
    @ResponseBody
    ReplyObj updateBom(HttpServletRequest request, @RequestParam(defaultValue = "", required = false, value = "json") String json
    ) {
        return bomService.updateBom(request, json);
    }


    /**
     * 修改BOM信息
     *
     * @param request
     * @param
     * @return
     */
    @RequestMapping("updateBomDetails")
    @ResponseBody
    public ReplyObj updateBomDetails(HttpServletRequest request,
                                     @RequestParam(defaultValue = "", required = false, value = "materialGoodsSpecsId") String materialGoodsSpecsId,
                                     @RequestParam(defaultValue = "", required = false, value = "recordDetailId") String recordDetailId) {
        return bomService.updateBomDetails(request, materialGoodsSpecsId, recordDetailId);
    }


    /**
     * 删除BOM信息
     *
     * @param request
     * @param bomId
     * @return
     */
    @RequestMapping("delBom")
    @ResponseBody
    ReplyObj delBom(HttpServletRequest request, @RequestParam(defaultValue = "", required = false, value = "bomId") String bomId
    ) {
        return bomService.delBom(request, bomId);
    }


    /**
     * 获取对应产品的BOM列表
     *
     * @param request
     * @param specsId
     * @return
     */
    @RequestMapping("getList")
    @ResponseBody
    ReplyObj getList(HttpServletRequest request, @RequestParam(defaultValue = "", required = false, value = "specsId") String specsId
    ) {
        if (WebUtils.checkStr(specsId)) {
            JpaQueryBuilder pb = Specifications.<Bom>and();
            pb.eq("goodsSpecs.id", specsId);
            return WebUtils.flushSuccess(bomRepository.findAll(pb.build()));
        } else {
            return WebUtils.flushFailure("");
        }
    }


    /**
     * 获取Bom的历史数据
     * @param request
     * @param specsId
     * @return
     */
    @RequestMapping("getBomHistory")
    @ResponseBody
    ReplyObj getBomHistory(HttpServletRequest request, @RequestParam(defaultValue = "", required = false, value = "specsId") String specsId
    ) {
        if (WebUtils.checkStr(specsId)) {
            return WebUtils.flushSuccess(bomRepository.getBomHistory(specsId));
        } else {
            return WebUtils.flushFailure("");
        }
    }


//    /**
//     * 获取历史BOM列表
//     * @param request
//     * @param specsId
//     * @return
//     */
//    @RequestMapping("getBom")
//    @ResponseBody
//    ReplyObj getBom(HttpServletRequest request, @RequestParam(defaultValue = "", required = false, value = "specsId") String specsId
//    ) {
//        if (WebUtils.checkStr(specsId)) {
//            List<Bom> bomList = bomRepository.getBom(specsId);
//            // 检查bomList是否为空
//            if (bomList == null || bomList.isEmpty()) {
//                return WebUtils.flushFailure("该产品未配置Bom");
//            }
//
//            return WebUtils.flushSuccess();
//        } else {
//            return WebUtils.flushSuccess();
//        }
//    }

    /**
     * 获取已启用的BOM
     *
     * @param request
     * @param specsId
     * @return
     */
    @RequestMapping("getStatusBom")
    @ResponseBody
    ReplyObj getStatusBom(HttpServletRequest request, @RequestParam(defaultValue = "", required = false, value = "specsId") String specsId
    ) {
        if (WebUtils.checkStr(specsId)) {
            List<Bom> bomList = bomRepository.getStatusBom(specsId, Bom.STATUS_RUN);

            // 检查bomList是否为空
            if (bomList == null || bomList.isEmpty()) {
                return WebUtils.flushFailure("该产品未配置Bom");
            }
            List<BomDetail> bomDetailList = bomDetailRepository.getByBomId(bomList.get(0).getId());

            // 不需要整个BomDetail的数据, 那非常的大, 提取需要的就可以了
            List<BomDetailVO> result = new ArrayList<>();
            for (BomDetail bomDetail : bomDetailList) {
                BomDetailVO bomDetailVO = new BomDetailVO();
                bomDetailVO.setId(bomDetail.getId());
                bomDetailVO.setBomId(bomDetail.getBom().getId());
                bomDetailVO.setLevel(bomDetail.getLevel());
                bomDetailVO.setSeq(bomDetail.getSeq());
                bomDetailVO.setGoodsSpecsId(bomDetail.getGoodsSpecsId());
                bomDetailVO.setMaterialSpecsName(bomDetail.getMaterialSpecsName());
                bomDetailVO.setMaterialSpecsCode(bomDetail.getMaterialSpecsCode());
                bomDetailVO.setMaterialGoodsName(bomDetail.getMaterialGoodsName());
                bomDetailVO.setMaterialGoodsCode(bomDetail.getMaterialGoodsCode());
                bomDetailVO.setSkuCode(bomDetail.getSkuCode());
                bomDetailVO.setUnit(bomDetail.getUnit());
                bomDetailVO.setUnitNum(bomDetail.getUnitNum());
                bomDetailVO.setMaterialTag(bomDetail.getMaterialTag());
                bomDetailVO.setMemo(bomDetail.getMemo());
                bomDetailVO.setParentId(bomDetail.getParentId());
                result.add(bomDetailVO);
            }
            return WebUtils.flushSuccess(result);
        } else {
            return WebUtils.flushSuccess();
        }
    }


    @RequestMapping("getBomInfo")
    @ResponseBody
    ReplyObj getBomInfo(HttpServletRequest request, @RequestParam(defaultValue = "", required = false, value = "specsId") String specsId
    ) {
        if (WebUtils.checkStr(specsId)) {
            Map<String, Object> resultMap = new HashMap<>();

            List<Bom> bomList = bomRepository.getStatusBom(specsId, Bom.STATUS_RUN);

            // 检查bomList是否为空
            if (bomList == null || bomList.isEmpty()) {
                return WebUtils.flushFailure("该产品未配置Bom或者没有Bom被启用");
            }
            List<BomDetail> bomDetailList = bomDetailRepository.getByBomId(bomList.get(0).getId());

            // 不需要整个BomDetail的数据, 那非常的大, 提取需要的就可以了
            List<BomDetailVO> resultList = new ArrayList<>();
            for (BomDetail bomDetail : bomDetailList) {
                BomDetailVO bomDetailVO = new BomDetailVO();
                bomDetailVO.setId(bomDetail.getId());
                bomDetailVO.setBomId(bomDetail.getBom().getId());
                bomDetailVO.setLevel(bomDetail.getLevel());
                bomDetailVO.setSeq(bomDetail.getSeq());
                bomDetailVO.setGoodsSpecsId(bomDetail.getGoodsSpecsId());
                bomDetailVO.setMaterialSpecsName(bomDetail.getMaterialSpecsName());
                bomDetailVO.setMaterialSpecsCode(bomDetail.getMaterialSpecsCode());
                bomDetailVO.setMaterialGoodsName(bomDetail.getMaterialGoodsName());
                bomDetailVO.setMaterialGoodsCode(bomDetail.getMaterialGoodsCode());
                bomDetailVO.setSkuCode(bomDetail.getSkuCode());
                bomDetailVO.setUnit(bomDetail.getUnit());
                bomDetailVO.setUnitNum(bomDetail.getUnitNum());
                bomDetailVO.setMaterialTag(bomDetail.getMaterialTag());
                bomDetailVO.setMemo(bomDetail.getMemo());
                bomDetailVO.setParentId(bomDetail.getParentId());
                resultList.add(bomDetailVO);
            }

            resultMap.put("bomList", resultList);

            Map<String, Object> bomInfo = bomRepository.getBomInfo(bomList.get(0).getId());
            resultMap.put("bomInfo", bomInfo);

            importBomDetailsRepository.updateGoodsSpecsId(bomList.get(0).getId());


            return WebUtils.flushSuccess(resultMap);
        } else {
            return WebUtils.flushFailure("没有物料信息，无法查询Bom信息");
        }
    }


    /**
     * 启用Bom表
     *
     * @param request
     * @param specsId
     * @param bomId
     * @return
     */
    @RequestMapping("enableBom")
    @ResponseBody
    ReplyObj enableBom(HttpServletRequest request,
                       @RequestParam(defaultValue = "", required = false, value = "specsId") String specsId,
                       @RequestParam(defaultValue = "", required = false, value = "bomId") String bomId
    ) {
        return bomService.enableBom(request, specsId, bomId);
    }


    /**
     * 获取对应id的BOM表信息
     *
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("getOne")
    @ResponseBody
    ReplyObj getOne(HttpServletRequest request, @RequestParam(defaultValue = "", required = false, value = "id") String id
    ) {
        if (WebUtils.checkStr(id)) {
            JpaQueryBuilder pb = Specifications.<Bom>and();
            pb.eq("bom.id", id);
            List<BomDetail> all = bomDetailRepository.findAll(pb.build());

            List<BomDetailVO> result = new ArrayList<>();
            for (BomDetail bomDetail : all) {
                BomDetailVO bomDetailVO = new BomDetailVO();
                bomDetailVO.setId(bomDetail.getId());
                bomDetailVO.setBomId(bomDetail.getBom().getId());
                bomDetailVO.setLevel(bomDetail.getLevel());
                bomDetailVO.setSeq(bomDetail.getSeq());
                bomDetailVO.setGoodsSpecsId(bomDetail.getGoodsSpecsId());
                bomDetailVO.setMaterialSpecsName(bomDetail.getMaterialSpecsName());
                bomDetailVO.setMaterialSpecsCode(bomDetail.getMaterialSpecsCode());
                bomDetailVO.setMaterialGoodsName(bomDetail.getMaterialGoodsName());
                bomDetailVO.setMaterialGoodsCode(bomDetail.getMaterialGoodsCode());
                bomDetailVO.setUnit(bomDetail.getUnit());
                bomDetailVO.setUnitNum(bomDetail.getUnitNum());
                bomDetailVO.setMaterialTag(bomDetail.getMaterialTag());
                bomDetailVO.setMemo(bomDetail.getMemo());
                bomDetailVO.setParentId(bomDetail.getParentId());
                result.add(bomDetailVO);
            }
            return WebUtils.flushSuccess(result);
        } else {
            return WebUtils.flushFailure("");
        }
    }


    @RequestMapping("uploadBomExcel")
    @ResponseBody
    ReplyObj uploadBomExcel(HttpServletRequest request,
                            @RequestParam(defaultValue = "", required = false, value = "loginId") String loginId,
                            @RequestParam(defaultValue = "", required = false, value = "companyId") String companyId,
                            @RequestParam(defaultValue = "", required = false, value = "bomName") String bomName,
                            @RequestParam(defaultValue = "", required = false, value = "bomMemo") String bomMemo) {

        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        MultipartFile uploadFile = multiRequest.getFile("uploadFiles");
        if (uploadFile.isEmpty() == false) {
            Boolean isEncrypt = false;
            try {
                if (WebUtils.checkStr(request.getParameter("isEncrypt"))) {
                    isEncrypt = Boolean.valueOf(request.getParameter("isEncrypt"));
                }
                if (!uploadFile.isEmpty()) {
                    //拿出现在应用的文件存储方式
                    FileResource fileResource = fileResourceRepository.getByApplyResource("七牛存储");
                    String uploadImplClass = fileResource.getImplClassName();
                    FileUploadSaveService fileUploadSaveService = (FileUploadSaveService) Class.forName(String.valueOf(uploadImplClass)).getDeclaredConstructor().newInstance();
                    AttachFile attachFile = fileUploadSaveService.upload(attachFileRepository, uploadFile, fileResource, isEncrypt);

                    ImportDataBatch importDataBatch = new ImportDataBatch();
                    importDataBatch.setFileName(attachFile.getName());
                    importDataBatch.setAttachFile(attachFile);
                    importDataBatch.setCreateTime(new Date());
                    Employee employee = employeeRepository.getById(loginId);
                    importDataBatch.setUploadUser(employee);
                    importDataBatch.setUploadCompanyId(companyId);
                    importDataBatch.setFileType(ImportDataBatch.TYPE_IMPORT_BOM);
                    importDataBatch.setStatus(ImportDataBatch.STATUS_SUBMIT_DOING);
                    ImportDataBatch save = importDataBatchRepository.save(importDataBatch);
                    // 创建并启动线程
                    UploadBomExcelThread uploadBomExcelThread = new UploadBomExcelThread(bomService, save, loginId, companyId, bomName, bomMemo);
                    uploadBomExcelThread.start();
                    return WebUtils.flushObjSuccess(attachFile);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return WebUtils.flushFailure();
            }
        }

        return WebUtils.flushFailure("文件上传失败，请重新选择文件进行提交上传");
    }


    /**
     * 新增BomDetail
     *
     * @param request
     * @param parentBomDetailId 要加的父类BomDetailId
     * @param goodsSpecsIds     添加的BomDetail列表的规格id是哪些
     * @return
     */
    @RequestMapping("addBomDetail")
    @ResponseBody
    ReplyObj addBomDetail(HttpServletRequest request,
                          @RequestParam(defaultValue = "", required = false, value = "parentBomDetailId") String parentBomDetailId,
                          @RequestParam(defaultValue = "", required = false, value = "goodsSpecsIds") List<String> goodsSpecsIds
    ) {
        return bomService.addBomDetail(request, parentBomDetailId, goodsSpecsIds);
    }


    /**
     * 删除BomDetail
     *
     * @param request
     * @param bomDetailId
     * @return
     */
    @RequestMapping("delBomDetail")
    @ResponseBody
    ReplyObj delBomDetail(HttpServletRequest request, @RequestParam(defaultValue = "", required = false, value = "bomDetailId") String bomDetailId) {
        bomDetailRepository.delBomDetail(bomDetailId);
        return WebUtils.flushSuccess();
    }


    /**
     * 修改BomDetail, 只是修改部分属性
     *
     * @param request
     * @param id
     * @param unitNum
     * @param materialTag
     * @param memo
     * @return
     */
    @RequestMapping("updateBomDetail")
    @ResponseBody
    ReplyObj updateBomDetail(HttpServletRequest request, @RequestParam(defaultValue = "", required = false, value = "id") String id,
                             @RequestParam(defaultValue = "", required = false, value = "unitNum") Double unitNum,
                             @RequestParam(defaultValue = "", required = false, value = "materialTag") String materialTag,
                             @RequestParam(defaultValue = "", required = false, value = "memo") String memo) {
        BomDetail targetBomDetail = bomDetailRepository.getById(id);
        targetBomDetail.setUnitNum(unitNum);
        targetBomDetail.setMaterialTag(materialTag);
        targetBomDetail.setMemo(memo);
        bomDetailRepository.save(targetBomDetail);
        return WebUtils.flushSuccess();
    }


}
